<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" layout:decorate="~{admin/layout}">

<head>
	<title>Sport Manage</title>
	<style>
	  #editor—wrapper {
	    border: 1px solid #ccc;
	    z-index: 100; /* 按需定义 */
	  }
	  #toolbar-container { border-bottom: 1px solid #ccc; }
	  #editor-container { height: 500px; }
	</style>
</head>

<body layout:fragment="content">
	<div class="card shadow">
		<div class="card-header border-bottom d-flex justify-content-between align-items-center">
			<h5 class="card-title mb-0">Sport List</h5>
			<div class="d-grid gap-2 d-md-block">
				<button class="btn btn-sm btn-primary" type="button" onclick="modifySportModal('')">New</button>
			</div>
		</div>
		<div class="card-body">
			<table id="sportTable"></table>
		</div>
		<!--<div class="card-footer pt-0">
			Footer
		</div>-->
	</div>
	<!---->
	<div class="modal fade" id="sportModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
		aria-hidden="true">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title" id="myModalLabel">Sport Setting</h4>
				</div>
				<div class="modal-body">
					<div class="row">
						<div class="col-md-12">
							<form id="sportForm">
								<input type="hidden" class="form-control" value="" id="sportId" name="sportId">
								<div class="mb-3 sportTypeDiv">
									<label class="form-label">Type</label>
									<select class="form-select" value="" id="sportType" name="sportType">
										<option value="0">Room</option>
										<option value="1">Site</option>
									</select>
								</div>
								<div class="mb-3 the-type  the-type-0" style="display: none;">
									<label class="form-label">The-Room</label>
									<select class="form-select" value="" id="sportRoomId" name="sportRoomId">
										<option th:each="room,roomStat:${rooms}" th:value="${room.roomId}" th:text="${room.roomTitle}"></option>
									</select>
								</div>
								<div class="mb-3 the-type  the-type-0" style="display: none;">
									<label class="form-label">The-Course</label>
									<select class="form-select" value="" id="sportCourseId" name="sportCourseId">
										<option th:each="course,courseStat:${courses}" th:value="${course.courseId}" th:text="${course.courseTitle}"></option>
									</select>
								</div>
								<div class="mb-3 the-type the-type-1" style="display: none;">
									<label class="form-label">The-Site</label>
									<select class="form-select" value="" id="sportSiteId" name="sportSiteId">
										<option th:each="site,siteStat:${sites}" th:value="${site.siteId}" th:text="${site.siteTitle}"></option>
									</select>
								</div>
								<div class="mb-3">
									<label class="form-label">Title</label>
									<input type="text" class="form-control" value="" id="sportTitle" name="sportTitle">
								</div>
								<div class="mb-3">
									<label class="form-label">Image</label>
									<input type="hidden"  value="" id="sportImg" name="sportImg">
									<div class="quickgo-file-main">
										<img src="" alt="Avatar">
										<div>
											<button>
												<span>Select Picture</span>
												<input type="file" onchange="MyUpload(this, 'sportImg');">
											</button>
										</div>
									</div>
								</div>
								<div class="mb-3">
									<label class="form-label">Describe</label>
									<textarea style="display: none;" id="sportDesc" name="sportDesc"></textarea>
									<div id="editor—wrapper">
									    <div id="toolbar-container"></div>
									    <div id="editor-container"></div>
									</div>
								</div>
								<!-- Save button -->
								<div class="d-flex justify-content-end mt-4">
									<button type="button" class="btn btn-default"
										onclick="closeSportModal()">Close</button>
									<button type="submit" class="btn btn-primary">Submit</button>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal -->
	</div>
	<script layout:fragment="script">
		var sportFormValidate = null, TYPE = null;
		const { createEditor, createToolbar } = window.wangEditor
		var editor = null
		$(document).ready(function () {
			sportFormValidate = 
			$("#sportForm").validate({
				rules: {
					sportId: {
						required: false
					},
					sportType: {
						required: true
					},
					sportTitle: {
						required: true
					},
				},
				submitHandler: function (form) {
					var formData = $(form).serialize();
					saveSport(formData);
					return false
				}
			})
			loadSportTable()
			$('#sportType').change(function(){
				changeType($(this).val())
			});
			const editorConfig = {
			    placeholder: 'Type here...',
			    MENU_CONF: {},
			    onChange(editor) {
			      const html = editor.getHtml()
			      //console.log('editor content', html)
			      $('#sportDesc').val(html)
			    }
			}
			editorConfig.MENU_CONF['uploadImage'] = {
			     server: ctx + '/file/uploadEditor',
			     fieldName: 'file',
			     onBeforeUpload(file) {
			        console.log('onBeforeUpload', file)
			
			        return file // will upload this file
			        // return false // prevent upload
			      },
			      onProgress(progress) {
			        console.log('onProgress', progress)
			      },
			      onSuccess(file, res) {
			        console.log('onSuccess', file, res)
			      },
			      onFailed(file, res) {
			        alert(res.message)
			        console.log('onFailed', file, res)
			      },
			      onError(file, err, res) {
			        alert(err.message)
			        console.error('onError', file, err, res)
			      },
			}
			editor = createEditor({
			    selector: '#editor-container',
			    html: '<p><br></p>',
			    config: editorConfig,
			    mode: 'simple',
			})
			const toolbarConfig = {}
			const toolbar = createToolbar({
			    editor,
			    selector: '#toolbar-container',
			    config: toolbarConfig,
			    mode: 'simple',
			})
			$('#sportModal').on('hidden.bs.modal', function () {
				editor.setHtml('')
			})
		});
		function loadSportTable() {
			$('#sportTable').bootstrapTable('destroy');
			$('#sportTable').bootstrapTable({
				url: "[[@{'/admin/sports'}]]",
				uniqueId: 'sportId',
				dataType: "json",
				pagination: true,
				pageSize: 10,
				queryParams: function (params) {
					var temp = {
						size: params.limit,
						page: (params.offset / params.limit),
						sort: params.sort,
						sortOrder: params.order,
						type: TYPE
					};
					return temp;
				},
				sidePagination: "server",
				pageList: [30, 50],
				columns: [{
					title: 'Sort',
					formatter: function (value, row, index) {
						var pageSize = $('#sportTable').bootstrapTable('getOptions').pageSize;
						var pageNumber = $('#sportTable').bootstrapTable('getOptions').pageNumber;
						return pageSize * (pageNumber - 1) + index + 1;
					}
				}, {
					field: 'sportType',
					title: 'Type',
					formatter: function (value, row, index) {
						return ['Room','Site'][value]
					}
				}, {
					field: 'sportTitle',
					title: 'Title',
					formatter: function (value, row, index) {
						return value
					}
				}
				, {
					field: 'sportImg',
					title: 'Image',
					formatter: function (value, row, index) {
						return '<img class="avatar-img rounded-2 avatar-sm" src=" ' + value + ' " alt="">'
					}
				}, {
					field: 'sportPublish',
					title: 'Published',
					formatter: function (value, row, index) {
						var pstr = 'Publish </br>' + row.sportPublishTime
						return ['Not', pstr][value]
					}
				}, {
					field: 'sportTime',
					title: 'Created',
					formatter: function (value, row, index) {
						return value
					}
				}, {
					title: 'Operate',
					field: 'sportId',
					class: 'text-center',
					width: '20%',
					formatter: function (value, row, index) {
						let res = ''
						res += '<button class="btn btn-sm btn-info" onclick="showSlot(\'' + value + '\')">Set-Slot</button>&nbsp;';
						res += '<button class="btn btn-sm btn-info" onclick="showReview(\'' + value + '\')">Reviews</button>&nbsp;';
						res += '<button class="btn btn-sm btn-warning" onclick="modifySportModal(\'' + value + '\')">Modify</button>&nbsp;';
						if(row.sportPublish == 0){
							res += '<button class="btn btn-sm btn-primary" onclick="toPublish(\'' + value + '\', 1)">Publish</button>&nbsp;';
						}else{
							res += '<button class="btn btn-sm btn-dark" onclick="toPublish(\'' + value + '\', 0)">Cancel</button>&nbsp;';
						}
						res += '<button class="btn btn-sm btn-danger " onclick="removeSport(\'' + value + '\')">Remove</button>';
						return res;
					}
				},],
				onPostBody: function (value) {
					$(".fixed-table-container").css('padding-bottom', '37px');
				}
			});
		}
		function showSlot(sportId){
			window.location.href = '[[@{/admin/slot?sportId=}]]' + sportId
		}
		function showReview(sportId){
			window.location.href = '[[@{/admin/review?sportId=}]]' + sportId
		}
		function closeSportModal() {
			sportFormValidate.resetForm()
			$('#sportModal').modal('hide')
		}
		function modifySportModal(sportId) {
			$(".quickgo-file-main").children("img").css("display", 'none')
			if (sportId) {
				var data = $("#sportTable").bootstrapTable('getRowByUniqueId', sportId);
				$('.sportTypeDiv').hide()
				changeType(data.sportType)
				$('#sportId').val(data.sportId)
				$('#sportType').val(data.sportType)
				$('#sportRoomId').val(data.sportRoomId)
				$('#sportCourseId').val(data.sportCourseId)
				$('#sportSiteId').val(data.sportSiteId)
				$('#sportTitle').val(data.sportTitle)
				$('#sportImg').val(data.sportImg)
				$('#sportDesc').val(data.sportDesc)
				editor.setHtml(data.sportDesc)
				if(data.sportImg){
					$(".quickgo-file-main").children("img").attr("src", data.sportImg).css("display", 'block')
				}
			} else {
				$('.sportTypeDiv').show()
				$('#sportId').val('')
				$('#sportType').val('')
				$('#sportRoomId').val('')
				$('#sportCourseId').val('')
				$('#sportSiteId').val('')
				$('#sportTitle').val('')
				$('#sportImg').val('')
				$('#sportDesc').val('')
				changeType('')
			}
			$('#sportModal').modal('show')
		}
		function changeType(type){
			$('#sportRoomId').val('')
			$('#sportCourseId').val('')
			$('#sportSiteId').val('')
			$('.the-type').hide()
			$('.the-type-' + type).show()
		}
		function saveSport(data) {
			if(!$('#sportImg').val()){
				layer.msg("Select Image");
				return null;
			}
			if(!$('#sportDesc').val()){
				layer.msg("Empty Desc");
				return null;
			}
			$.post(ctx + "/admin/saveSport", data, function (resp) {
				if (resp.status == 0) {
					loadSportTable();
					$('#sportModal').modal('hide');
				}
				layer.msg(resp.msg);
			})
		}
		function toPublish(sportId, type) {
			layer.msg("Do you want to " + (type==1?'Publish':'Cancel') + " it", {
				title: 'tip', icon: 3, btn: ["Confirm", "Cancel"],
				yes: function () {
					$.ajax({
						type: "get",
						url: ctx + "/admin/publishSport",
						data: {
							"sportId": sportId,
							"publish": type,
						},
						success: function (resp) {
							if (resp.status == 0) {
								loadSportTable()
							}
							layer.msg(resp.msg);
						}
					});
				},
				btn2: function () {
					// layer.msg("Cancel");
				}
			});
		}
		function removeSport(sportId) {
			layer.msg("Do you want to delete it", {
				title: 'tip', icon: 3, btn: ["Confirm", "Cancel"],
				yes: function () {
					$.ajax({
						type: "get",
						url: ctx + "/admin/delSport",
						data: {
							"sportId": sportId,
						},
						success: function (resp) {
							if (resp.status == 0) {
								loadSportTable()
							}
							layer.msg(resp.msg);
						}
					});
				},
				btn2: function () {
					// layer.msg("Cancel");
				}
			});
		}
	</script>
</body>

</html>